package com.hh.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hh.common.Const;
import com.hh.domain.ResponseResult;
import com.hh.entity.CourseInfor;
import com.hh.entity.Login;
import com.hh.entity.Optional;
import com.hh.entity.Teach;
import com.hh.entity.dto.*;
import com.hh.enums.AppHttpCodeEnum;
import com.hh.mapper.CourseInforMapper;
import com.hh.mapper.OptionalMapper;
import com.hh.mapper.QueryCurriculumMapper;
import com.hh.mapper.TeachMapper;
import com.hh.service.CourseInforService;
import com.hh.service.LoginService;
import com.hh.service.OptionalService;
import com.hh.utils.ObjectUtils;
import com.hh.utils.RedisCache;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
/*
 * @author huxy
 * @since 2022年10月16日
 * */
@RestController
@RequestMapping("/course")
public class CourseController {
    @Autowired
    QueryCurriculumMapper queryCurriculumMapper;
    @Autowired
    CourseInforMapper courseInforMapper;
    @Autowired
    RedisCache redisCache;
    @Autowired
    OptionalService optionalService;
    @Autowired
    OptionalMapper optionalMapper;
    @Autowired
    LoginService loginService;
    @Autowired
    TeachMapper teachMapper;
    /*
     * 查询课程表
     * @Params 学生ID studentId
     * @return 课程列表（QueryCurriculumDTO Dto数据传输类型）
     * */
    @RequestMapping("/queryCurriculum/{studentId}")
    public ResponseResult queryCurriculum(@PathVariable("studentId") String studentId){
        List<QueryCurriculumDTO> queryCurriculumDTO = queryCurriculumMapper.selectCurriculum(studentId);
        if (ObjectUtils.isEmpty(queryCurriculumDTO)){
            return ResponseResult.errorResult(AppHttpCodeEnum.NONE_COURSE.getCode(),"未找到课程");
        }else {
            return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),queryCurriculumDTO);
        }
    }

    /*
    * 查询可选课程
    * @Params 学生ID studentId
    * @return 课程列表（CourseInfor 实体类型）
    * */
    @RequestMapping("/queryOptional/{studentId}")
    public ResponseResult queryOptional(@PathVariable("studentId") String studentId){
        List<CourseInfor> courseInfors = queryCurriculumMapper.selectOptional(studentId);
        if (ObjectUtils.isEmpty(courseInfors)){
            return ResponseResult.errorResult(AppHttpCodeEnum.NONE_COURSE.getCode(),"未找到课程");
        }else {
            String key = studentId + Const.OPTIONAL_COURSE;
            String courseInforscover = JSON.toJSONString(courseInfors);
            redisCache.setCacheObject(key,courseInforscover,120, TimeUnit.SECONDS);
            return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),courseInfors);
        }
    }

    /*
     * 从可选课程中选择课程
     * @Params 学生ID studentId， 课程ID courseId
     * @return 选课结果
     * */
    @RequestMapping("/optionalCourse/{studentId}/{courseId}")
    public ResponseResult optionalCourse(@PathVariable("studentId") String studentId,
                                    @PathVariable("courseId") Integer courseId){
        String key = studentId + Const.OPTIONAL_COURSE;
        if (ObjectUtils.isEmpty(redisCache.getCacheObject(key))){
            queryOptional(studentId);
        }
        Object courseInforObj = redisCache.getCacheObject(key);
        List<CourseInfor> courseInfors = JSON.parseArray(courseInforObj.toString(), CourseInfor.class);
        for (CourseInfor courseInfor : courseInfors) {
            if (courseInfor.getCourseId().equals(courseId) || courseInfor.getCourseId() == courseId) {
                Integer result = queryCurriculumMapper.insertOptionalCourse(courseId, studentId);
                Integer insertTeacherRe = queryCurriculumMapper.insertOptionalCourseTeacher(courseId, studentId);
                if (insertTeacherRe>0){
                if (result > 0) {
                    return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(), "选课成功");
                }}else{
                    return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(), "选课成功,当前未分配教师");
                }
            }
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.NONE_COURSE.getCode(), "选课失败");
        }

    /*
     * 查询已选课程
     * @Params 学生ID studentId
     * @return 已选课程列表
     * */
    @RequestMapping("/querySelected/{studentId}")
    public ResponseResult querySelected(@PathVariable("studentId") String studentId){
        List<CourseInfor> selected = queryCurriculumMapper.getSelected(studentId);
        if (ObjectUtils.isEmpty(selected)){
            return ResponseResult.errorResult(AppHttpCodeEnum.NONE_COURSE.getCode(),"未找到课程");
        }else {
            return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),selected);
        }
    }

    /*
     * 退选课程
     * @Params 学生ID studentId， 课程ID courseId
     * @return 退选结果
     * */
    @RequestMapping("/refundCourse/{studentId}/{courseId}")
    public ResponseResult refundCourse(@PathVariable("studentId") String studentId,
                                         @PathVariable("courseId") Integer courseId){
        Integer refundresult = queryCurriculumMapper.deleteCourse(courseId, studentId);
        if (refundresult > 0){
            return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),"退课成功");
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.NONE_COURSE.getCode(),"未找到课程");
        }
    }

    /*
     * 管理员添加课程
     * @Params 学生ID studentId， 课程ID courseId
     * @return 退选结果
     * */
    @RequestMapping(value = "/addCourseInfo/{loginId}",method = RequestMethod.POST)
    public ResponseResult addCourseInfo(@RequestBody CourseInfor courseInfor,@PathVariable String loginId){

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("Login_id",loginId);
        Login loginInfo = loginService.getOne(queryWrapper);
        //判断角色是否为管理员
        if (loginInfo.getRoleId() == 3){
            try {
                int insert = courseInforMapper.insert(courseInfor);
                if (insert > 0){
                    return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),"添加课程成功");
                }
            }catch (Exception e){
                return ResponseResult.errorResult(AppHttpCodeEnum.ADD_COURSE_ERR.getCode(),AppHttpCodeEnum.ADD_COURSE_ERR.getMsg());
            }


        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.ROLE_AUTHORIZE_ERR.getCode(),AppHttpCodeEnum.ROLE_AUTHORIZE_ERR.getMsg());
        }
        return ResponseResult.okResult();
    }
    /*
     * 管理员删除课程
     * @Params 学生ID studentId， 课程ID courseId
     * @return 退选结果
     * */
    @RequestMapping(value = "/delCourseInfo/{loginId}/{courseId}",method = RequestMethod.POST)
    public ResponseResult delCourseInfo(@PathVariable Integer courseId,@PathVariable String loginId){

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("Login_id",loginId);
        Login loginInfo = loginService.getOne(queryWrapper);
        QueryWrapper queryWrapper1 = new QueryWrapper();
        queryWrapper1.eq("Course_id",courseId);
        //判断角色是否为管理员
        if (loginInfo.getRoleId() == 3){
            try {
                int delete = courseInforMapper.delete(queryWrapper1);
                if (delete > 0){
                    return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),"删除课程成功");
                }
            }catch (Exception e){
                return ResponseResult.errorResult(AppHttpCodeEnum.DEL_COURSE_ERR.getCode(),AppHttpCodeEnum.DEL_COURSE_ERR.getMsg());
            }


        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.ROLE_AUTHORIZE_ERR.getCode(),AppHttpCodeEnum.ROLE_AUTHORIZE_ERR.getMsg());
        }
        return ResponseResult.okResult();
    }

    /*
     * 教师查看授课表
     * @Params 学生ID studentId， 课程ID courseId
     * @return 退选结果
     * */
    @RequestMapping(value = "/findTeach/{teacherId}")
    public ResponseResult findTeach(@PathVariable String teacherId){
        List<TeachDTO> teach = teachMapper.findTeach(teacherId);
        if (ObjectUtils.isEmpty(teach)){
            return new ResponseResult(AppHttpCodeEnum.DEL_COURSE_ERR.getCode(),AppHttpCodeEnum.DEL_COURSE_ERR.getMsg());
        }
        return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),teach);
    }

    /*
     * 教师查看授课表
     * @Params 学生ID studentId， 课程ID courseId
     * @return 退选结果
     * */
    @RequestMapping(value = "/findCourseStudent/{courseId}/{teacherId}")
    public ResponseResult findCourseStudent(@PathVariable Integer courseId,@PathVariable String teacherId){
        List<OptionalCourseStudentDTO> optionalCourseStudentDTOS = optionalMapper.findCourseStudent(courseId,teacherId);
        if (ObjectUtils.isEmpty(optionalCourseStudentDTOS)){
            return new ResponseResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),AppHttpCodeEnum.SYSTEM_ERROR.getMsg());
        }
        return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),optionalCourseStudentDTOS);
    }

    /*
     * 教师录入成绩
     * @Params 学生ID studentId， 课程ID courseId
     * @return 退选结果
     * */
    @RequestMapping(value = "/inputResults",method = RequestMethod.POST)
    public ResponseResult inputResults(@RequestBody Optional optional){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("Login_id",optional.getTeacherId());
        Login loginInfo = loginService.getOne(queryWrapper);
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("Course_id",optional.getCourseId());
        wrapper.eq("Student_id",optional.getStudentId());
        wrapper.eq("Teacher_id",optional.getTeacherId());
        wrapper.eq("results",null);
        if (loginInfo.getRoleId() == 2 || loginInfo.getRoleId().equals(2)){
            int update = optionalMapper.update(optional, wrapper);
            if (update > 0){
                return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),AppHttpCodeEnum.SUCCESS.getMsg());
            }else{
                return new ResponseResult(AppHttpCodeEnum.INPUT_ERR.getCode(),AppHttpCodeEnum.INPUT_ERR.getMsg());
            }
        }
        return new ResponseResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),AppHttpCodeEnum.SYSTEM_ERROR.getMsg());
    }

    /*
     * 学生查询成绩
     * @Params 学生ID studentId， 课程ID courseId
     * @return 退选结果
     * */
    @RequestMapping(value = "/findResults")
    public ResponseResult findResults(@RequestBody Optional optional){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("Login_id",optional.getStudentId());
        Login loginInfo = loginService.getOne(queryWrapper);
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("Student_id",optional.getStudentId());
        if (loginInfo.getRoleId() == 1 || loginInfo.getRoleId().equals(1)){
            List<OptionalForResultsDTO> resultsList = optionalMapper.findResultsList(optional.getStudentId());
            if (!ObjectUtils.isEmpty(resultsList)){
                return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),resultsList);
            }
        }
        return new ResponseResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),AppHttpCodeEnum.SYSTEM_ERROR.getMsg());
    }

    /*
     * 管理员修改成绩
     * @Params 学生ID studentId， 课程ID courseId
     * @return 退选结果
     * */
    @RequestMapping(value = "/updateResults/{loginId}",method = RequestMethod.POST)
    public ResponseResult updateResults(@RequestBody Optional optional,@PathVariable String loginId){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("Login_id",loginId);
        Login loginInfo = loginService.getOne(queryWrapper);
        UpdateWrapper wrapper = new UpdateWrapper();
        wrapper.eq("Course_id",optional.getCourseId());
        wrapper.eq("Student_id",optional.getStudentId());
        wrapper.eq("Teacher_id",optional.getTeacherId());
        if (loginInfo.getRoleId() == 3 || loginInfo.getRoleId().equals(3)){
            int update = optionalMapper.update(optional, wrapper);
            if (update > 0){
                return new ResponseResult(AppHttpCodeEnum.SUCCESS.getCode(),AppHttpCodeEnum.SUCCESS.getMsg());
            }
        }
        return new ResponseResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),AppHttpCodeEnum.SYSTEM_ERROR.getMsg());
    }

}
